<template>
  <div>
    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #code="scope">
              <span>{{ scope.row.code + (scope.row.build === lastBuild ? '(当前版本)' : '') }}</span>
            </template>

            <template #force_update="scope">
              <DictTag v-model="scope.row.force_update" :circle="false" dict-type="sys_yes_no"/>
            </template>

            <template #enabled="scope">
              <DictTag v-model="scope.row.enabled" :circle="false" dict-type="sys_enabled"/>
            </template>

            <template #operations="scope">
              <el-popconfirm
                  :key="scope.row.id"
                  cancel-button-text="放弃"
                  confirm-button-text="确定"
                  icon="WarningFilled"
                  title="是否确认修改当前记录的状态?"
                  width="300"
                  @confirm="handleToggleEnabled(scope.row)">
                <template #reference>
                  <el-button :type="scope.row.enabled ? 'danger' : 'success'" link>{{ scope.row.enabled ? '禁用' : '启用' }}</el-button>
                </template>
              </el-popconfirm>
              <el-button link type="primary" @click="handleVersionShow(scope.row.id)">编辑</el-button>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

  </div>
</template>

<script lang="tsx" setup>
import { computed, onBeforeMount, ref } from 'vue';
import { QueryForm } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { hasPermission } from '@/utils/permission.ts';
import { bytesToSize, computedOperateWidth } from '@/utils';
import { appVersionList, appVersionUpdate } from '@/api/api-app.ts';
import { DictTag } from '@/components/dict-tag';

const props = defineProps({
  appId: {
    type: Number,
    required: true
  },
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);
const lastBuild = ref(0);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0;
  if (hasPermission('app:info:version:update')) count += 2;
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'code', label: '版本', width: 160, align: 'right', sortable: 'custom'},
  {prop: 'build', label: 'Build', width: 120, align: 'right', sortable: 'custom'},
  {prop: 'file_size', label: '大小', width: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{bytesToSize(val)}</span>},
  {prop: 'download_count', label: '下载次数', width: 120, align: 'right', sortable: 'custom'},
  {prop: 'channel_type', label: '渠道类型', width: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'message', label: '更新说明', minWidth: 180, align: 'right', sortable: 'custom'},
  {prop: 'force_update', label: '强制更新', width: 120, align: 'right', sortable: 'custom'},
  {prop: 'enabled', label: '是否有效', width: 120, align: 'right', sortable: 'custom'},
  {prop: 'create_time', label: '发布时间', width: 180, align: 'right', sortable: 'custom'},
  {prop: 'update_time', label: '更新时间', width: 180, align: 'right', sortable: 'custom'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'center', headerAlign: 'center'},)
  }
  // 重置查询表单
  handleResetQueryForm();
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 查询数据
    const {data} = await appVersionList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      app_id: props.appId,
    });
    // 结果转换
    tableData.value = data.list.list;
    totalCount.value = data.list.pages.total_count;
    lastBuild.value = data.last_build;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  clearSelection();
  handleResetForm();
};

// 对外提供部分方法
defineExpose({handleSearch});

/** 处理启用禁用切换 */
const handleToggleEnabled = (row: any) => {
  if (!row || row.id <= 0) return
  let params = row;
  params.enabled = !params.enabled
  appVersionUpdate(params).then(() => {
    handleSearch();
    ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
  });
};

/** 通知父组件 进行编辑操作 */
const emit = defineEmits(['update']);
const handleVersionShow = (id: number) => {
  emit('update', 2, id);
};
</script>

<style lang="scss" scoped>

</style>
